import {
  ResponseCode,
  ResponseMessage,
  type BaseResponse,
  type DataResponse,
  type PaginationResponse,
  type PaginationData,
} from '../types/response.js';
import { GlobalContext } from './context.js';

export class Response {
  /**
   * 成功响应
   */
  static success<T = unknown>(message?: string, data?: T): void {
    const ctx = GlobalContext.getCurrentContext();
    const response: BaseResponse | DataResponse<T> = {
      code: ResponseCode.SUCCESS,
      message: message || ResponseMessage[ResponseCode.SUCCESS],
      timestamp: Date.now(),
      data,
    };
    ctx.body = response;
  }

  /**
   * 分页响应
   */
  static pagination<T>(message?: string, data?: PaginationData<T>): void {
    const ctx = GlobalContext.getCurrentContext();
    const response: PaginationResponse<T> = {
      code: ResponseCode.SUCCESS,
      message: message || ResponseMessage[ResponseCode.SUCCESS],
      timestamp: Date.now(),
      data: data || {
        list: [],
        total: 0,
        page: 0,
        pageSize: 0,
      },
    };
    ctx.body = response;
  }

  /**
   * 错误响应
   */
  static error(
    code: ResponseCode = ResponseCode.INTERNAL_ERROR,
    message = 'Internal Server Error'
  ): void {
    const ctx = GlobalContext.getCurrentContext();
    const response: BaseResponse = {
      code,
      message: message || ResponseMessage[code],
      timestamp: Date.now(),
    };
    // 设置相应的 HTTP 状态码
    switch (code) {
      case ResponseCode.UNAUTHORIZED:
        ctx.status = 401;
        break;
      case ResponseCode.FORBIDDEN:
        ctx.status = 403;
        break;
      case ResponseCode.NOT_FOUND:
        ctx.status = 404;
        break;
      case ResponseCode.VALIDATION_ERROR:
        ctx.status = 422;
        break;
      case ResponseCode.INTERNAL_ERROR:
        ctx.status = 500;
        break;
      default:
        ctx.status = 200;
    }
    ctx.body = response;
  }

  /**
   * 验证错误响应
   */
  static validationError(message: string): void {
    this.error(ResponseCode.VALIDATION_ERROR, message);
  }

  /**
   * 未授权响应
   */
  static unauthorized(message?: string): void {
    this.error(ResponseCode.UNAUTHORIZED, message || 'Unauthorized');
  }

  /**
   * 禁止访问响应
   */
  static forbidden(message?: string): void {
    this.error(ResponseCode.FORBIDDEN, message || 'Forbidden');
  }

  /**
   * 资源未找到响应
   */
  static notFound(message?: string): void {
    this.error(ResponseCode.NOT_FOUND, message || 'Not Found');
  }

  /**
   * 服务器错误响应
   */
  static serverError(message?: string): void {
    this.error(ResponseCode.INTERNAL_ERROR, message || 'Internal Server Error');
  }
}
